package instantmessenger;

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Enumeration;
import java.util.Vector;

public class ChatServerImpl implements ChatServer {

    Vector<instantmessenger.Listener> listeners = new Vector<instantmessenger.Listener>();

    public ChatServerImpl() {}

    public void sendMessage(String user, String message) {

        Enumeration elements = listeners.elements();
        while (elements.hasMoreElements()){
            Listener cl = (Listener) (elements.nextElement());
            try {
                System.out.println("Sent message from " + user + ", message: " + message);
                cl.messageReceived(user, message);
            } catch (RemoteException ex) {
                listeners.remove(cl);
            }
        }
    }

    public void removeChatListener(Listener cl) throws RemoteException{
        System.out.println("remove chat listener");
        listeners.remove(cl);
    }

    public void addChatListener(Listener cl) throws RemoteException {
        System.out.println("add chat listener");
        listeners.add(cl);
    }



    public static void main(String args[]) {

        try {
            ChatServerImpl obj = new ChatServerImpl();
            ChatServer stub = (ChatServer) UnicastRemoteObject.exportObject(obj, 0);

            try {
                java.rmi.registry.LocateRegistry.createRegistry(1099);
                System.out.println("Starting registry");
            } catch (RemoteException ex) {
                System.out.println("Error starting registry");
            }
            
            // Bind the remote object's stub in the registry
            Registry registry = LocateRegistry.getRegistry();
            registry.bind("ChatServer", stub);

            System.err.println("Server ready");
        } catch (Exception e) {
            System.err.println("Server exception: " + e.toString());
            e.printStackTrace();
        }
    }
}